import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TcpServe {
    private ServerSocket serversocket = null;
    public TcpServe(int Port) throws IOException {
        serversocket = new ServerSocket(Port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        while (true){
            Socket socket = serversocket.accept();
            ProcessNection(socket);
        }
    }

    private void ProcessNection(Socket socket) throws IOException {
        System.out.printf("[%s:$d]","客户端上线",socket.getInetAddress(),socket.getPort());
        //创建输入流和输出流分别用来读取和输出数据
        try(InputStream inputStream = socket.getInputStream();
        OutputStream outputStream = socket.getOutputStream()) {
            //创建 scanner 来读取数据
            Scanner scanner = new Scanner(inputStream);
            //将字符串直接写入到socket的输出流中发送给客户端。
            PrintWriter writer = new PrintWriter(outputStream);
            while(true){
                //检查客户端是否下线
                if (!scanner.hasNext()){
                    System.out.printf("[%s:%d] 客户端下线\n",socket.getInetAddress(),socket.getPort());
                }
                //读取数据
                String request = scanner.next();
                //处理数据
                String resoponse = process(request);
                //输出数据给客户端
                writer.println(resoponse);
                //冲刷缓冲区
                writer.flush();
                //打印客户端信息
                System.out.printf("[%s:%d] req:%s resp:%s\n",socket.getInetAddress(),socket.getPort(),
                        request,resoponse);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                //关闭与客户端的socket连接
                socket.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpServe server = new TcpServe(1010);
        server.start();
    }
}
